<?php

namespace App\Logic;

use App\Model\ApplyAnchor;
use App\Model\Live;
use App\Model\User;
use App\Model\UserModelAnchor;
use App\Service\EmailService;
use App\Service\SmsService;
use App\Utils\Enum\SceneEnum;
use App\Utils\Enum\UserEnum;
use App\Utils\Log;
use Exception;

class AdminAnchorLogic
{
    /**
     * 获取主播列表
     * @param $input
     * @return array
     */
    public static function anchorList($input): array
    {
        [$pageNum, $pageSize, $offset] = parsePageParams($input);
        $query = UserModelAnchor::query()->when(!empty($input['query']['keyword']), function ($query) use ($input) {
            $query->where('userid', AdminUserLogic::findUserId($input['query']['keyword']));
        });
        $total = $query->count();
        if ($total) {
            $records = $query->with(['user', 'live', 'assistant', 'column'])->offset($offset)->limit($pageSize)->orderBy('listorder')->orderBy('id')->get()->toArray();
        }
        return [
            'total' => $total,
            'pages' => ceil($total / $pageSize),
            'records' => $records ?? []
        ];
    }

    /**
     * 获取主播详情
     * @param $userId
     * @return array
     */
    public static function anchorDetail($userId): array
    {
        return UserModelAnchor::query()->where('userid', $userId)->with(['user', 'live'])->first()->toArray();
    }

    /**
     * 入驻列表
     * @param $input
     * @return array
     */
    public static function anchorSettled($input): array
    {
        [$pageNum, $pageSize, $offset] = parsePageParams($input);
        $query = ApplyAnchor::query()->when(isset($input['query']['status']) && $input['query']['status'] != '', function ($q) use ($input) {
            $q->where('audit_status', (int)$input['query']['status']);
        });
        $total = $query->count();
        if ($total) {
            $records = $query->with(['user'])->orderBy('id', 'desc')->offset($offset)->limit($pageSize)->get()->toArray();
        }
        return [
            'total' => $total,
            'pages' => ceil($total / $pageSize),
            'records' => $records ?? []
        ];
    }

    /**
     * 处理申请入驻
     * @throws Exception
     */
    public static function anchorAuditSettled($id, $input): true
    {
        $info = ApplyAnchor::query()->where('id', $id)->first();
        if (!$info) {
            throw new Exception('未找到该申请');
        }
        if ($info['audit_status'] != 0) {
            throw new Exception('该申请已经处理过了');
        }

        if ($input['status'] == 1 && !User::query()->where(['id' => $input['assistantUserId'], 'role_id' => UserEnum::USER_TYPE_ASSIST])->exists()) {
            throw new Exception('直播助理不存在');
        }
        $data = [
            'audit_status' => $input['status'],
            'audit_mark' => $input['remark'] ?? '',
            'audit_time' => time(),
        ];
        try {
            ApplyAnchor::query()->where('id', $id)->update($data);
            if ($input['status'] == 1) {
                User::query()->where('id', $info['userid'])->update([
                    'role_id' => UserEnum::USER_TYPE_ANCHOR
                ]);
                UserModelAnchor::create([
                    'userid' => $info['userid'],
                    'column_id' => $info['live_column_id'],
                    'assistant_userid' => $input['assistantUserId'], //助理用户ID
                ]);
            }
        } catch (Exception $e) {
            Log::error(sprintf('主播入驻申请处理失败:%s', $e->getMessage()));
            throw new Exception('处理失败');
        }
        $user = User::query()->where('id', $info['userid'])->first();
        try {
            if (!empty($user['email'])) {
                EmailService::send($user['mail'], $input['status'] == 1 ? SceneEnum::APPLY_SUCC : SceneEnum::APPLY_FAIL, ['title' => '主播入驻']);
            } else {
                SmsService::send($user['mobile'], $input['status'] == 1 ? SceneEnum::APPLY_SUCC : SceneEnum::APPLY_FAIL, ['title' => '主播入驻']);
            }
        } catch (Exception $e) {
            Log::error(sprintf('主播入驻申请处理通知失败:%s', $e->getMessage()));
        }
        return true;
    }

    /**
     * 快速修改参数
     * @param $userId
     * @param $field
     * @param $value
     * @return true
     * @throws Exception
     */
    public static function updateField($userId, $field, $value): true
    {
        if (!in_array($field, ['listorder'])) {
            throw new Exception('不支持修改该值');
        }
        UserModelAnchor::query()->where('userid', $userId)->update([$field => $value]);
        Live::query()->where('userid', $userId)->update([$field => $value]);
        return true;
    }
}